package com.strato.saas.user.interceptor.v1_0_0;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.mvc.api.v1_0_0.control.HttpInvoker;
import com.strato.mvc.api.v1_0_0.control.HttpInvokerInterceptor;
import com.strato.mvc.api.v1_0_0.control.PathVariableCollector;
import com.strato.mvc.api.v1_0_0.model.ModelAndView;
import com.strato.mvc.api.v1_0_0.user.Principal;
import com.strato.mvc.api.v1_0_0.user.UserContext;
import com.strato.mvc.api.v1_0_0.util.RequestMeta;

@OsgiService
public class UserContextInterceptor implements HttpInvokerInterceptor {

	private static final String USER_KEY_IN_SESSION = "_strato_user_";
	private static final int ORDER = 111;
	
	@Override
	public int getOrder() {
		return ORDER;
	}

	@Override
	public boolean canHandle(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, RequestMeta meta, HttpInvoker invoker) {
		return true;
	}

	@Override
	public boolean beforeInvocation(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc,ModelAndView mav, HttpInvoker invoker) {
		Principal principal=(Principal) request.getSession().getAttribute(Principal.ATTR_PRINCIPAL_IN_SESSION);
		if(principal!=null){
			String userId=principal.getUserId();
			Object user=request.getSession().getAttribute(USER_KEY_IN_SESSION);
			UserContext.setUser(user);
			UserContext.set(userId);
			UserContext.setPrincipal(principal);
		}
		return true;
	}

	@Override
	public void invocationSuccess(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, ModelAndView mav, HttpInvoker invoker) {

	}

	@Override
	public void invokeFinally(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, HttpInvoker invoker) {
		UserContext.set(null);
		UserContext.setUser(null);
	}

	@Override
	public void invocationFailed(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, Exception e, HttpInvoker invoker) {
	}

}
